package com.hankol.newretail.fragment

import android.view.LayoutInflater
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseLazyFragment
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.toast
import com.baselibrary.manager.DialogManager.showCoinDialog
import com.baselibrary.manager.LoadingManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.MarginDecoration
import com.hankol.newretail.PaySuccessActivity
import com.hankol.newretail.R
import com.hankol.newretail.SelectPayWayActivity
import com.hankol.newretail.adapter.StoreGoodsAdapter
import com.hankol.newretail.adapter.order.MyOrderListAdapter
import com.hankol.newretail.bean.CancelReasonListBean
import com.hankol.newretail.bean.GoodListBean
import com.hankol.newretail.bean.MyOrderListBean
import com.hankol.newretail.databinding.FragmentMyOrderBinding
import com.hankol.newretail.utils.RetailPopUtils
import com.hankol.newretail.viewmodel.OrderAboutViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MyOrderFragment(var status: Int = -1) : BaseLazyFragment(false) {
    private lateinit var binding: FragmentMyOrderBinding
    private lateinit var viewModel: OrderAboutViewModel
    private val mMyOrderListAdapter: MyOrderListAdapter by lazy { MyOrderListAdapter() }
    var page = 1
    private var hasnext: Boolean = false
    private var isEmpty = false
    private var clickOrderBean: MyOrderListBean? = null
    private var clickOrderPos = -1
    private val mRecommendAdapter: StoreGoodsAdapter by lazy { StoreGoodsAdapter() }
    private var keyword = ""


    fun setKeyWord(keyword: String) {
        this.keyword = keyword
    }

    companion object {
        //状态:-1-全部， 0-待付款，1-待发货，2-待收货）,5-已完成
        fun newInstance(status: Int = -1): MyOrderFragment {
            return MyOrderFragment(status)
        }
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        viewModel = getFragmentViewModelProvider(this).get(OrderAboutViewModel::class.java)
        binding = getDataBinding<FragmentMyOrderBinding>()
        initView()
        initListener()
        initObserver()
    }


    private fun initObserver() {
        viewModel.orderDataLD.observe(requireActivity(), Observer {
            binding.smartOrder.finishRefresh()
            binding.smartOrder.finishLoadMore()
            if (it == null || it.data.isNullOrEmpty()) {
                //无数据
                if (page == 1) {
                    mMyOrderListAdapter.setNewData(emptyList())
                }
                setEmptyView()
            } else {
                if (it.data.checkNotNull()) {
                    hasnext = it.hasnext
                    if (page == 1) {
                        binding.rvOrderList.adapter = mMyOrderListAdapter
                        mMyOrderListAdapter.setNewData(it.data)
                    } else {
                        mMyOrderListAdapter.addData(it.data)
                    }
                    page++
                }
                if (binding.rvOrderList.layoutManager is GridLayoutManager) {
                    binding.rvOrderList.layoutManager = LinearLayoutManager(requireContext())
                    binding.rvOrderList.removeItemDecoration(deco)
                }
            }
        })

        viewModel.cancelOrderLD.observe(this, Observer {
            "订单取消成功".toast()
            //取消订单
            if (clickOrderPos != -1) {
                //进入订单详情
                val hashMap = HashMap<String, Any>()
                hashMap[Constants.KEY_ORDER_ID] = mMyOrderListAdapter.data[clickOrderPos].poId
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
                mMyOrderListAdapter.remove(clickOrderPos)
                clickOrderPos = -1
                setEmptyView()

            }
        })
        viewModel.delOrderLD.observe(requireActivity(), Observer {
            LoadingManager.hideProgress(requireActivity())
            //删除订单
            if (clickOrderPos != -1) {
                mMyOrderListAdapter.remove(clickOrderPos)
                clickOrderPos = -1
                setEmptyView()

            }
        })
        //确认收货
        viewModel.confirmReciveLD.observe(requireActivity(), Observer {
            LoadingManager.hideProgress(requireActivity())
//                CommonBusiness.shareSuccess(requireActivity() as BaseActivity,14,"收货成功")
            if (it.rewardScore > 0) {
                showCoinDialog(requireActivity(), "收货成功", it.rewardScore)
            }
//            val hashMap = HashMap<String, Any>()
//            hashMap[Constants.KEY_ORDER_ID] = mMyOrderListAdapter.data[clickOrderPos].poId
//            ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
            if (status != -1) {
                if (clickOrderPos != -1) {
                    mMyOrderListAdapter.remove(clickOrderPos)
                    clickOrderPos = -1
                    setEmptyView()
                }
            } else {
                //更改状态
                if (clickOrderPos != -1) {
                    mMyOrderListAdapter.data[clickOrderPos].status = 5
                    mMyOrderListAdapter.notifyItemChanged(clickOrderPos)
                }
            }
        })
        //取消订单 弹窗 理由列表
        viewModel.cancelOrderReasonLD.observe(this, Observer {
            cancelOrder(it)
        })

        viewModel.guessYouLikeLD.observe(this, Observer {
            hideLoadingDialog()
            binding.smartOrder.finishRefresh()
            if (it.data.checkNotNull()) {
                hasnext = it.hasnext
                binding.smartOrder.finishLoadMore()
                if (page == 1) {
                    mRecommendAdapter.setNewData(it.data)
                } else {
                    mRecommendAdapter.addData(it.data)
                }
                page++
            } else {
                binding.smartOrder.finishLoadMore()
            }
        })
        //纯酒币（无现金）_电商订单_生成支付订单
        viewModel.onlyScoreOrderLD.observe(this, Observer {
            EventBusUtils.sendNotify(MessageBus.msgId_pay_success)
            val hashMap = java.util.HashMap<String, Any>()
            hashMap[PaySuccessActivity.KEY_POIDS] = it.poids.checkValue()
            hashMap[PaySuccessActivity.KEY_PAY_PRICE_SUM] = "${it.payPriceSum}"
            hashMap[PaySuccessActivity.KEY_SCORE_DEDUCTPRICE_SUM] = "${it.scoreDeductPriceSum}"
            hashMap[PaySuccessActivity.KEY_SHOULD_REWARD_SCORE] = "${it.shouldRewardScore}"
            ARouterUtils.jump(ActivityRouter.NEW_RETAIL.PAY_SUCCESS, hashMap)
            AppManager.getAppManager().finishActivity()
        })
    }

    private fun initView() {

        mRecommendAdapter.setOnItemClickListener { adapter, view, position ->
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val goodListBean = adapter.data[position] as GoodListBean
                //商品详情
                val map = java.util.HashMap<String, Any>()
                map[Constants.GOODS_DETAIL_ID] = goodListBean.id
                map[Constants.GOODS_DETAIL_SOURCE] = "订单页猜你喜欢"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
            }
        }
        mMyOrderListAdapter.setOnItemClickListener { adapter, view, position ->
            val orderBean = adapter.data[position] as MyOrderListBean
            if (!DoubleClickHelper.isOnDoubleClick()) {
                //进入订单详情
                val hashMap = HashMap<String, Any>()
                hashMap[Constants.KEY_ORDER_ID] = orderBean.poId
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
            }
        }
        mMyOrderListAdapter.setOnItemChildClickListener { adapter, view, position ->
            clickOrderPos = position
            clickOrderBean = mMyOrderListAdapter.data[position]
            when (view.id) {
                R.id.tv_order_cancel -> {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        if (TimeUtil.getCurrentTimeMillis() > clickOrderBean!!.overtime) {
                            "订单已关闭，请重新下单".toast()
                            if (status != -1) {
                                mMyOrderListAdapter.remove(position)
                                setEmptyView()
                            } else {
                                mMyOrderListAdapter.data[position].status = 6
                                mMyOrderListAdapter.notifyItemChanged(position)
                            }
                            return@setOnItemChildClickListener
                        }
                        viewModel.reqCancelOrderReasonList()
                    }
                }
                R.id.tv_order_store_name -> {//进入酒窖详情
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        clickOrderBean?.let {
                            val hashMap = java.util.HashMap<String, Any>()
                            hashMap["id"] = "${it.shopId}"
                            hashMap["dealerCode"] = "${it.dealerCode}"
                            ARouterUtils.jump(ActivityRouter.WINE_CELLAR.WINCE_CELLAR_DETAIL, hashMap)
                        }
                    }
                }
                R.id.rl_order_multiple, R.id.ll_price_num, R.id.rl_order_list_item -> {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        val hashMap = HashMap<String, Any>()
                        hashMap[Constants.KEY_ORDER_ID] = clickOrderBean!!.poId
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
                    }
                }
                //状态：0-待付款（创建），1-待发货（已付款），2-待收货（已发货），3-待评价（已收货），5-已完成，6-已关闭
                else -> {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        when (clickOrderBean!!.status) {
                            0 -> {
                                if (TimeUtil.getCurrentTimeMillis() > clickOrderBean!!.overtime) {
                                    "订单已关闭，请重新下单".toast()
                                    if (status != -1) {
                                        mMyOrderListAdapter.remove(position)
                                        setEmptyView()
                                    } else {
                                        mMyOrderListAdapter.data[position].status = 6
                                        mMyOrderListAdapter.notifyItemChanged(position)
                                    }
                                    return@setOnItemChildClickListener
                                }
                                //判断是否需要支付
                                if (clickOrderBean!!.shouldPayPrice > 0) {
                                    val hashMap = HashMap<String, Any>()
                                    hashMap[SelectPayWayActivity.KEY_POIDS] = "[${clickOrderBean!!.poId}]"
                                    hashMap[SelectPayWayActivity.KEY_OVERTIME] = clickOrderBean!!.overtime
                                    hashMap[SelectPayWayActivity.KEY_SHOULD_PAY_PRICE] = clickOrderBean!!.price
                                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.SELECT_PAY_WAY, hashMap)
                                } else {
                                    //直接纯酒币支付
                                    onlyCoinPay("[${clickOrderBean!!.poId}]")
                                }
                            }
                            2 -> {
                                if (clickOrderBean!!.receiveOvertime != 0L && TimeUtil.getCurrentTimeMillis() > clickOrderBean!!.receiveOvertime) {
                                    "订单已收货，请勿重复操作".toast()
                                    if (status != -1 && status != 5) {
                                        mMyOrderListAdapter.remove(position)
                                        setEmptyView()
                                    } else {
                                        mMyOrderListAdapter.data[position].status = 5
                                        mMyOrderListAdapter.notifyItemChanged(position)
                                    }
                                    return@setOnItemChildClickListener
                                }
                                if (clickOrderBean?.receiveOvertime == 0L) {
                                    //有正在处理的售后单
                                    PopUtils.showOkCancelDialog(requireActivity(), "订单存在售后\n继续收货，将撤销售后申请", object : PopUtils.ICallBack {
                                        override fun clickOk() {
                                            //确定
                                            LoadingManager.showProgress(requireActivity(), "请稍后...")
                                            clickOrderBean?.let {
                                                viewModel.requestConfirmRecive(it.poId.toString())
                                            }
                                        }

                                        override fun clickCancel() {}
                                    })
                                    LoadingManager.hideProgress(requireActivity())
                                } else {
                                    PopUtils.showOkCancelDialog(requireActivity(), "确认收货\n检查商品无误后，再进行确认收货", object : PopUtils.ICallBack {
                                        override fun clickOk() {
                                            //确定
                                            LoadingManager.showProgress(requireActivity(), "请稍后...")
                                            clickOrderBean?.let {
                                                viewModel.requestConfirmRecive(it.poId.toString())
                                            }
                                        }

                                        override fun clickCancel() {}
                                    })
                                }
                            }
                            6 -> {
                                deleteOrder("${clickOrderBean?.poId}")
                            }
                        }
                    }
                }
            }
        }
    }

    private fun onlyCoinPay(poids: String) {
        //不需要支付 直接跳转 支付成功页
        viewModel.reqCreateScoreOrder(poids)
    }

    //删除订单
    private fun deleteOrder(poid: String) {
        PopUtils.showOkCancelDialog(requireActivity(), "确认删除该订单？", object : PopUtils.ICallBack {
            override fun clickOk() {
                LoadingManager.showProgress(requireActivity(), "请稍后...")
                viewModel.requestDelOrder(poid)
            }

            override fun clickCancel() {}
        }, false, "确认", "取消", true)
    }

    private fun cancelOrder(reasonList: List<CancelReasonListBean>) {
        //取消订单
        RetailPopUtils.showCancelOrderDialog(requireActivity(), reasonList, object : RetailPopUtils.ICallBack4CancelOrderSelectReson {
            override fun onClickOk(isRebackCart: Boolean, cancellationId: Int) {
                clickOrderBean?.let {
                    viewModel.reqCancelOrder(it.poId.toString(), cancellationId, if (isRebackCart) 1 else 0)
                }
            }
        })
    }

    fun loadData(isReply: Boolean = false) {
        if (isReply) {
            page = 1
        }
        viewModel.requestOrderList(status, keyword, page)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_my_order
    }

    override fun lazyLoadData() {
        page = 1
        loadData()
    }

    fun onRefreshData() {
        page = 1
        loadData()
    }

    fun initListener() {
        binding.smartOrder.setOnRefreshListener {
            page = 1
            loadData()
        }
        binding.smartOrder.setOnLoadMoreListener {
            if (hasnext) {
                if (isEmpty) {
                    viewModel.reqGuessYouLikeGoodList(page)
                } else {
                    loadData()
                }
            } else {
                binding.smartOrder.finishLoadMore()
            }
        }
    }

    val deco by lazy { MarginDecoration(activity, 5) }
    private fun setEmptyView() {
        isEmpty = true
        //如果是搜索订单 不显示猜你喜欢占位
        if (mMyOrderListAdapter.data.size == 0 && keyword.isNullOrEmpty()) {
            viewModel.reqGuessYouLikeGoodList(page)
            mRecommendAdapter.removeAllHeaderView()
            val headView = LayoutInflater.from(activity).inflate(R.layout.layout_shopcart_empty_head, null)
            mRecommendAdapter.addHeaderView(headView)
            binding.rvOrderList.layoutManager = GridLayoutManager(activity, 2)
            binding.rvOrderList.removeItemDecoration(deco)
            binding.rvOrderList.addItemDecoration(deco)
            binding.rvOrderList.adapter = mRecommendAdapter
        } else {
            mMyOrderListAdapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_ORDER_LIST, binding.rvOrderList, "暂无订单")
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        when (messageBus.codeType) {
            MessageBus.msgId_del_order -> {
                if (status == -1) {
                    val poid = messageBus.param1
                    //删除订单
                    for (i in mMyOrderListAdapter.data.indices) {
                        if ("${(mMyOrderListAdapter.data[i] as MyOrderListBean).poId}" == poid) {
                            mMyOrderListAdapter.data.removeAt(i)
                            mMyOrderListAdapter.notifyItemRemoved(i)
                            setEmptyView()
                        }
                    }
                }
            }
            MessageBus.msgId_close_order_detail -> {
                if (status == 2) {
                    //待收货
                    val mStatus = messageBus.param1
                    if (mStatus != status) {
                        //删除订单
                        for (i in mMyOrderListAdapter.data.indices) {
                            if ("${(mMyOrderListAdapter.data[i] as MyOrderListBean).poId}" == "${clickOrderBean?.poId}") {
                                mMyOrderListAdapter.data.removeAt(i)
                                mMyOrderListAdapter.notifyItemRemoved(i)
                                setEmptyView()
                            }
                        }
                    }
                }
            }
            MessageBus.msgId_confirm_receive_success, MessageBus.msgId_pay_success, MessageBus.msgId_commit_order_success, MessageBus.msgId_order_cancel_success -> {
                //支付成功、确认收货成功   刷新
                page = 1
                loadData()
            }
//            MessageBus.msgId_search_order -> {
//                //搜索订单
//                if (status == -1) {
//                    keyword = messageBus.param1.toString()
//                    onRefreshData()
//                }
//            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}